<template>
    <div class="container">
        <waterfall class="image-area" :style="_autoHeightStyle" column-width="150"  column-count="auto" left-gap="20" column-gap="5">
            <cell v-for="(img,index) in imgs">
                <div class="image-panel">
                    <image @click="preview(index)" class="image-i" :src="img.thumbUrl"></image>
                </div>
                <yx-icon v-if="readonly" ucode="e652" @click="deleImg(index)" size="xxs" color="red" class="del-image"></yx-icon>
            </cell>
            <cell v-if="readonly">
                <div @click="uploadImg" class="image-i add-img">
                    <yx-icon @click="uploadImg" ucode="e646" color="#999"></yx-icon>
                </div>
            </cell>
        </waterfall>
    </div>
</template>

<script>
    import YxIcon from 'Components/yx-icon'
    import Apis from 'Apis'
    import appConfig from 'Config/application_config'
    import utils from 'Utils/utils'

    const stream = weex.requireModule('stream') || {}


    export default {
        name: "yx-upload",
        components: {YxIcon},

        model: {
            prop: 'value',
            event: 'getVal'
        },

        props: {
            value: {
                type: String,
                default: ''
            },
            readonly: {
                type: Boolean,
                default: false
            }
        },

        data(){
            return {
                imgs:[],
                serverUrl:'',
                loadUrl:'',
                currentVal:'',
                isTargetEvent: false,
                storeImgs:[]
            }
        },

        computed:{
            _autoHeightStyle:function(){

                if(this.imgs.length == 0 ) {
                    return {height:200}
                }else{

                    var index = parseInt((this.imgs.length+1)/4)

                    var remain =  (this.imgs.length+1) % 4

                    if(remain > 0 ) {
                        index += 1
                    }

                    return {height: index * 200}
                }

            }
        },

        created(){
            this.serverUrl = `${appConfig.BASE_API}${Apis.upload}`
            this.loadUrl = `${appConfig.BASE_API}/fileDeal/file`
            this.currentVal = this.value
            this.loadImg()
        },

        methods:{

            /**
             * 浏览图片
             */
            preview(index){
                if (this.imgs.length == 0) {
                    return
                }

                let arr = []
                for (let i in this.imgs){
                    arr.push(this.imgs[i].url)
                }

                this.$image.preview({
                    index: index,             // 所点击图片下标
                    images: arr,        // 图片的网络地址
                })
            },

            /**
             * 删除图片
             * @param index
             */
            deleImg(index){
                this.imgs.splice(index,1)
                var arr = this.currentVal.split(',')
                let newValue = ''

                for (let i in arr){
                    if (index == i) {
                        continue
                    }
                    newValue += ',' +arr[i]
                }

                if (utils.isNotEmpty(newValue)) {
                    newValue = newValue.substring(1)
                }

                this.currentVal = newValue

                this.isTargetEvent = true

                this.$emit('getVal', newValue)


            },

            /**
             * 上传图片
             */
            uploadImg(){
                var self = this
                this.$image.pickAndUpload({
                    url: this.serverUrl,                     // 自定义图片上传地址，默认上传地址是 eros.native.js 中的 image 地址
                    maxCount: 9,                 // 一次最多可选择图片数量 最大支持9张 默认是1
                    imageWidth: 1000,            // 图片宽度（根据宽度按比例裁剪）可以不传默认为 800px
                    allowCrop: true,             // 是否允许编辑（只有当 maxCount == 1时 此参数才会生效） 默认是false
                    params: {},                  // 传递的参数
                    header: {}                   // 自定义请求 header
                })
                    .then(resData => {
                        console.log(resData)    // [url1, url2...]


                        for (let index in resData){
                            let ele = resData[index]

                            if (ele.status !== 1) {
                                continue
                            }

                            if (ele.data.length == 0) {
                                continue
                            }
                            let imgInfo = ele.data[0]

                            var imgObj = {
                                url:imgInfo.url,
                                thumbUrl:imgInfo.thumbUrl
                            }
                            self.imgs.push(imgObj)

                            self.addImgKey(imgInfo.key)

                            self.storeImgs[imgInfo.key] = imgObj
                        }

                        this.isTargetEvent = true
                        self.$emit('getVal', self.currentVal)

                    }, error => {
                        this.$notice.toast({
                            message: JSON.stringify(error)
                        })
                    })
            },

            /**
             * 添加图片key值
             */
            addImgKey(key){
                if (utils.isNotEmpty(this.currentVal)){
                    this.currentVal += ',' + key
                }else{
                    this.currentVal = key
                }
            },

            /**
             * 加载图片
             */
            loadImg(){
                var self = this

                if (utils.isEmpty(this.currentVal)){
                    return
                }

                this.imgs = []

                let imgKeys = this.currentVal.split(',')

                let exitImgs = {}
                let notExitKeys = ''
                for (let x in imgKeys){
                    let k = imgKeys[x]
                    if (this.storeImgs[k]) {
                        exitImgs[k] = this.storeImgs[k]
                    }else{
                        notExitKeys += ','+ k
                    }
                }



                if (utils.isEmpty(notExitKeys)) {
                    for (let j in imgKeys){
                        this.imgs.push(exitImgs[imgKeys[j]])
                    }
                }else{

                    notExitKeys = notExitKeys.substring(1)

                    stream.fetch({
                        method: 'GET',
                        url: `${this.serverUrl}?keys=${notExitKeys}`,
                        type:'json'
                    }, function(ret) {


                        if (ret.status !== 200) {
                            this.$notice.toast({
                                message: JSON.stringify('请求资源图片出错')
                            })
                            return
                        }
                        let resData = ret.data

                        if (resData.status !== 1) {
                            this.$notice.toast({
                                message: resData.msg
                            })
                            return
                        }


                        let imgData = resData.data

                        for (let index in imgData){
                            let img = imgData[index]
                            let imgObj = {
                                url:img.url,
                                thumbUrl:img.thumbUrl
                            }
                            self.storeImgs[img.key] = imgObj
                        }

                        for (let b in imgKeys){
                            self.imgs.push(self.storeImgs[imgKeys[b]])
                        }

                    })
                }
            }

        },
        mounted (){

        },

        watch: {
            value (val){

                if (this.isTargetEvent){
                    this.value = val
                }else{
                    this.currentVal = val
                    this.loadImg()
                }

                this.isTargetEvent = false
            }
        }
    }
</script>

<style lang="scss" scoped>
    @import "yx-upload";

</style>
